﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace Inspector
{
    /// <summary>   
    ///  消息拦截器   
    /// </summary>   
    public class Inspector : IClientMessageInspector, IDispatchMessageInspector
    {
        void IClientMessageInspector.AfterReceiveReply(ref Message reply, object correlationState)
        {
            //Console.WriteLine("客户端接收到的回复：\n{0}", reply.ToString());
            return;
        }

        object IClientMessageInspector.BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            //Console.WriteLine("客户端发送请求前的SOAP消息：\n{0}", request.ToString());
            // 插入验证信息   
            MessageHeader hdclient = MessageHeader.CreateHeader("key", "http://Vanglen", "client1");
            MessageHeader hdUserName = MessageHeader.CreateHeader("u", "http://Vanglen", "admin");
            MessageHeader hdPassWord = MessageHeader.CreateHeader("p", "http://Vanglen", "321321");

            request.Headers.Add(hdUserName);
            request.Headers.Add(hdPassWord);
            return null;
        }

        object IDispatchMessageInspector.AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            //Console.WriteLine("服务器端：接收到的请求：\n{0}", request.ToString());
            // 栓查验证信息   
            if (request.Headers.Count > 1)
            {
                //string n = ((System.Xml.XmlBaseReader)(((System.ServiceModel.Security.SecurityVerifiedMessage)(request)).cachedDecryptedBodyContentReader)).LocalName;
                //instanceContext.
                string un = request.Headers.GetHeader<string>("u", "http://Vanglen");
                string ps = request.Headers.GetHeader<string>("p", "http://Vanglen");
                if (un == "admin" && ps == "1231")
                {
                    Console.WriteLine("用户名和密码正确。");
                }
                else
                {
                    throw new Exception("验证失败，滚吧！");
                }
            }

            //instanceContext.set = CommunicationState.Faulted;

            return null;
        }

        void IDispatchMessageInspector.BeforeSendReply(ref Message reply, object correlationState)
        {
            //Console.WriteLine("服务器即将作出以下回复：\n{0}", reply.ToString());
            return;
        }
    }

}
